<template>
  <div>
    <a-spin :spinning="loading">
      <div class="title">
        <div class="title_top">
          <div class="title_top_left">每日三省</div>
          <div class="title_top_right cursor_pointer" @click="addFakeNote">
            <img class="title_top_right_img" src="@/assets/images/home/plus-square.png" alt="" />
            <div class="title_top_right_text">添加内容</div>
          </div>
        </div>
      </div>

      <a-date-picker style="margin-top:10px" @change="onChange" v-model="currdate" valueFormat="YYYY-MM-DD" />
      <div class="top_his">
        <img @click="choDate(-1)" class="top_his_pic cursor_pointer" src="@/assets/images/home/leftarr.png" alt="" />
        <div
          v-for="(day, index) in currentArr.days"
          :key="day.id"
          :class="day.flag ? 'top_his_datea' : 'top_his_date'"
          class="cursor_pointer"
          @click="selectDay(index)"
        >
          <div :class="day.flag ? 'top_his_date_worda' : 'top_his_date_word'">
            <div>{{ day.date }}</div>
            <div v-if="allRecordTime.includes(day.id)" class="tip_bulb"><a-icon type="bulb" theme="filled" /></div>
          </div>
          <div :class="day.flag ? 'top_his_date_worda' : 'top_his_date_word'">{{ day.day }}</div>
        </div>
        <img @click="choDate(+1)" class="top_his_pic cursor_pointer" src="@/assets/images/home/rightarr.png" alt="" />
      </div>

      <div class="bottom_list">
        <div v-if="noteBook.records && noteBook.records.length > 0">
          <div class="bottom_item" v-for="(item, index) in noteBook.records" :key="index">
            <div class="bottom_item_content">
              <div class="bottom_item_index">
                {{ index + 1 + '.' }}
              </div>
              <div v-if="!item.isEdit" class="rightt beyond_hiding">{{ item.notetext }}</div>
              <div v-else class="rightt" :class="{ 'rightt_edit': item.isEdit }">
                <a-textarea
                  class="rightt_textarea"
                  v-model="item.notetext"
                  placeholder="请输入记录内容"
                  :auto-size="{ minRows: 2, maxRows: 3 }"
                  :maxLength="3000"
                  @blur="saveNoteBook(item)"
                />
              </div>
              <div class="icon" v-if="!item.isEdit">
                <img class="leftt left_icon" src="@/assets/images/home/updata.png" @click="modifyNote(item)" alt="" />
                <a-popconfirm title="确定删除吗？" ok-text="是" cancel-text="否" @confirm="deleteNote(item)">
                  <img class="leftt" src="@/assets/images/home/delete.png" alt="" />
                </a-popconfirm>
              </div>
              <!-- <div class="icon" v-else >
                <div class="ant_icon_save_div">
                  <a-icon class="ant_icon ant_icon_save"  type="check" />
                  <a-button type="primary" icon="check" class="ant_icon_save_btn" @click="saveNoteBook(item)">保存</a-button>
                </div>
                <a-popconfirm
                  title="确认撤销吗？"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="callBackModify(item)"
                >
                  <a-icon class="ant_icon ant_icon_rollback" type="close" />
                </a-popconfirm>
              </div> -->
            </div>
          </div>
        </div>
        <div v-else>
          <a-empty style="margin-top:20px" />
        </div>
      </div>
    </a-spin>
  </div>
</template>

<script>
import util from '@/views/home_page/util.js'
import { APP_USER, APP_DEPT } from '@/store/mutation-types.js'
import storage from 'store'
import { getNoteBookList, deleteNoteBook, saveNoteBook, getAllRecordTime } from '@/api/home/apl_note_book.js'
import moment from 'moment'
import { nanoid } from 'nanoid'
export default {
  name: 'right_bottom',

  data() {
    return {
      dateCurrent: new Date(), // 正选择的当前日期
      dateCurrentStr: '', // 正选择日期的 id
      dateMonth: '1月', // 正显示的月份
      dateListArray: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
      currentArr: [], //显示的数据
      currentind: 0, //索引位置
      currdate: null,
      activeKey: 1,
      currentUser: storage.get(APP_USER), // 登录人信息
      currentDept: storage.get(APP_DEPT), // 登录人部门

      list: [{}, {}, {}],
      loading: false,
      // 当前用户所有编辑的时间
      allRecordTime: [],
      // 当前时间的日记数据
      noteBook: {}
    }
  },
  created() {
    var that = this
    var d = new Date()
    this.initDate() // 日历组件程序
    this.getNoteBookList()
    this.getAllRecordTime()
  },
  watch: {
    currdate(val) {
      this.getNoteBookList()
    },
    deep: true,
    immediate: true
  },
  methods: {
    onChange(date, dateString) {
      this.currdate = dateString
      this.currentArr = this.calculateDate(date)
      for (var i = 0; i < 7; i++) {
        if (this.currentArr.days[i].id == dateString) {
          this.currentArr.days[i].flag = true
        }
      }
    },

    selectDay(index) {
      // 查询当前激活的那个日期
      let activeDay = 0
      for (let index = 0; index < this.currentArr.days.length; index++) {
        if (this.currentArr.days[index].flag) {
          activeDay = index
        }
      }
      this.choDate(index - activeDay)
    },
    choDate(index) {
      for (var i = 0; i < 7; i++) {
        if (this.currentArr.days[i].flag) {
          if (i + index == -1 || i + index == 7) {
            var activeDay = new Date(this.currentArr.days[i].id)
            var yesterday = new Date(activeDay)
            if (i + index == -1) {
              yesterday.setDate(activeDay.getDate() - 7)
            } else {
              yesterday.setDate(activeDay.getDate() + 7)
            }
            this.currentArr = this.calculateDate(yesterday)
            if (i + index == 7) {
              this.currentArr.days[0].flag = true
              this.currdate = this.currentArr.days[0].id
            } else if (i + index == -1) {
              this.currentArr.days[6].flag = true
              this.currdate = this.currentArr.days[6].id
            }
            break
          }
          this.currentArr.days[i].flag = false
          this.currentArr.days[i + index].flag = true
          this.currdate = this.currentArr.days[i + index].id
          break
        }
      }
    },
    // 日历部分
    initDate() {
      var d = new Date()
      var month = util.addZero(d.getMonth() + 1)
      var day = util.addZero(d.getDate())

      this.currentArr = this.calculateDate(d)
      // 默认激活当前的时间
      let filterItem = this.currentArr.days.filter(element => element.id == this.$moment(d).format("yyyy-MM-DD"))[0];
      if (filterItem) {
        filterItem.flag = true
        this.currdate = filterItem.id
      } else {
          // 默认第一天
      this.currentArr.days[0].flag = true
      this.currdate = this.currentArr.days[0].id
      }

      this.dateCurrent = d
      this.dateCurrentStr = d.getFullYear() + '-' + month + '-' + day
      this.dateMonth = month + '月'
    },
    // 获取这周从周日到周六的日期
    calculateDate(_date) {
      var first = util.FirstDayInThisWeek(_date)
      console.log(first)
      var d = {
        month: first.getMonth() + 1,
        days: []
      }
      for (var i = 0; i < 7; i++) {
        var dd = util.DateAddDay(first, i)
        var day = util.addZero(dd.getDate()),
          month = util.addZero(dd.getMonth() + 1)
        d.days.push({
          day: day,
          id: dd.getFullYear() + '-' + month + '-' + day,
          date: this.dateListArray[i],
          flag: false
        })
      }
      return d
    },

    // 查询后台数据-查询当前登录人员当前时间的笔记
    getNoteBookList() {
      this.loading = true
      let params = {
        f_userid: this.currentUser.userId,
        f_notetime: this.currdate,
        sort: 'sort',
        order: 'asc'
      }
      getNoteBookList(params)
        .then(res => {
          if (res.code !== 0) {
            this.$message.error('查询每日记录失败')
          } else {
            this.noteBook = res.data
            // 对当前的记录进行编辑字段设置
            if (this.noteBook.records && this.noteBook.records.length > 0) {
              this.noteBook.records.forEach(element => {
                // element.isEdit = false;
                this.$set(element, 'isEdit', false)
                this.$set(element, 'isSaved', true)
                this.$set(element, 'constNoteText', element.notetext)
              })
            }
          }
        })
        .catch(err => {
          this.noteBook = {}
          console.log(err, '查询每日记录失败')
        })
        .finally(() => {
          this.loading = false
        })
      // 查询全部编辑过的时间
      this.getAllRecordTime()
    },

    // 查询当前人所有编辑过的时间
    getAllRecordTime() {
      getAllRecordTime({ userid: this.currentUser.userId })
        .then(res => {
          if (res.code !== 0) {
            this.$message.error('查询每日记录失败')
          } else {
            this.allRecordTime = res.data
          }
        })
        .catch(err => {
          this.allRecordTime = []
          console.log(err, '查询每日记录失败')
        })
        .finally(() => {})
    },
    /**
     * 修改笔记内容
     */
    modifyNote(item) {
      item.isEdit = true
    },
    /**
     * 删除笔记
     */
    deleteNote(item) {
      if (item.isSaved) {
        deleteNoteBook({ id: item.id })
          .then(res => {
            if (res.code !== 0) {
              this.$message.error('删除失败')
            } else {
              this.getNoteBookList()
            }
          })
          .catch(err => {
            console.log(err, '删除失败')
          })
          .finally(() => {})
      } else {
        this.noteBook.records = this.noteBook.records.filter(v => v.id != item.id)
      }
    },
    /**
     * 撤回编辑
     */
    callBackModify(item) {
      if (item.isSaved) {
        item.isEdit = false
        item.notetext = item.constNoteText
      } else {
        this.noteBook.records = this.noteBook.records.filter(v => v.id != item.id)
      }
    },
    /**
     * 修改或新增笔记
     */
    saveNoteBook(item) {
      saveNoteBook(item)
        .then(res => {
          if (res.code !== 0) {
            this.$message.error('保存失败')
          } else {
            this.getNoteBookList()
          }
        })
        .catch(err => {
          console.log(err, '保存失败')
        })
        .finally(() => {})
    },
    /**
     * 前端页面假添加数据
     *
     */
    addFakeNote() {
      if (this.noteBook.records && this.noteBook.records.length > 0) {
        if (this.noteBook.records.some(item => item.isSaved == false)) {
          this.$message.warn('当前已存在一条未保存数据')
          return
        }
      }
      let note = {
        id: nanoid(),
        userid: this.currentUser.userId,
        username: this.currentUser.fullname,
        isEdit: true,
        isSaved: false,
        notetime: this.currdate,
        notetext: ''
      }
      this.noteBook.records.push(note)
    }
  }
}
</script>

<style lang="less">
.bottom_list {
  display: flex;
  flex-direction: column;
  .bottom_item {
    display: flex;
    flex-direction: row;
    margin-top: 30px;
    justify-content: center;
    align-items: center;
    .bottom_item_content {
      padding-bottom: 13px;
      border-bottom: 1px solid #f5f5f5;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      width: 100%;

      .bottom_item_index {
        font-size: 16px;
        font-family: Source Han Sans CN;
        font-weight: 400;
        color: #2c2c2c;
        margin-right: 30px;
      }

      .rightt {
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #2c2c2c;
        margin-right: auto;

        width: 75%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        display: inline-block;

        .rightt_textarea {
          font-size: 20px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #2c2c2c;
          margin-right: auto;
        }

      }
      .rightt_edit  {
        width: 100%;
      }
      .icon {
        float: right;
        width: 20%;
        // margin-left: 30px;
        // margin-right: 20px;
        .left_icon {
          margin-right: 40px;
          margin-left: 10px;
        }
        .ant_icon {
          font-size: 22px;
        }
        .ant_icon_rollback {
          margin-left: 20px;
        }
        .ant_icon_save_div {
          display: inline-block;
          margin-left: 10px;
        }
        .ant_icon_save_div:hover .ant_icon_save {
          display: none;
        }
        .ant_icon_save_div:hover .ant_icon_save_btn {
          display: inline-block;
        }
        .ant_icon_save {
          margin-right: 10px;
          margin-left: 30px;
          display: inline-block;
        }
        .ant_icon_save_btn {
          display: none;
          border-radius: 9px;
          background: #0072C6;
        }
      }
      .leftt {
        height: 20px;
        width: 20px;
        margin-right: 10px;
      }
    }
  }
}
.top_his {
  margin-top: 20px;
  display: flex;
  padding: 12px 32px;
  align-items: center;
  flex-direction: row;
  justify-content: space-around;
  background: #e7e7e7;
  .top_his_pic {
    height: 20px;
    width: 20px;
  }
  .top_his_date {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    .top_his_date_word {
      font-size: 18px;
      font-family: PingFang SC;
      font-weight: bold;
      display: flex;
      align-items: self-end;
      text-align: right;
      justify-content: flex-end;
    }
  }
  .top_his_datea {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    border: 1px solid #5698d4;
    padding: 10px;
    background-color: #5698d4;
    .top_his_date_worda {
      font-size: 18px;
      font-family: PingFang SC;
      font-weight: bold;
      color: #fafcfd;
      display: flex;
      align-items: self-end;
      text-align: right;
      justify-content: flex-end;
      background-color: #5698d4;
    }
  }
  .tip_bulb {
    margin-left: 5px;
    text-align: right;
    color: #ffcc22;
  }
}

.title {
  display: flex;
  flex-direction: column;
  .title_num {
    margin-top: 25px;
    display: flex;
    padding: 24px 82px;
    flex-direction: row;
    justify-content: space-around;
    background: #e7e7e7;
  }
  .title_top {
    padding-bottom: 16px;
    border-bottom: 3px solid #f5f5f5;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    .title_top_left {
      font-size: 23px;
      font-family: PingFang SC;
      font-weight: 800;
      color: #2c2c2c;
    }
    .title_top_right {
      display: flex;
      flex-direction: row;
      align-items: center;
      .title_top_right_img {
        margin-right: 13px;
        width: 20px;
        height: 20px;
      }
      .title_top_right_text {
        font-size: 20px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #666666;
      }
    }
  }
  .title_item {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 30px 0;
    border-bottom: 1px solid #f5f5f5;

    .title_item_left {
      font-size: 20px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #2c2c2c;
    }
    .title_item_right {
      font-size: 20px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #696969;
    }
  }
}

::v-deep .ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab-active {
  height: 40px;
  color: white;
  background: #0072c6;
  border-color: #e8e8e8;
  border-bottom: 1px solid #fff;
}
</style>